import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {InfoCircleOutlined} from '@ant-design/icons';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card, Row,Col, Tabs,message,Divider,Tooltip} from 'antd';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule } from '../service';
import styles from '../style.less';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;
const {TabPane} = Tabs;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataImgFormValues: any
  common: any
  imageValues: any
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate,dataImgFormValues,imageValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureVideo, setPictureVideo] = useState<any[]>([]);
  const [uploadVideoChanged, setUploadVideoChanged] = useState<boolean>(false);
  const [pictureAudio, setPictureAudio] = useState<any[]>([]);
  const [uploadAudioChanged, setUploadAudioChanged] = useState<boolean>(false);
  const [pictureFile, setPictureFile] = useState<any[]>([]);
  const [uploadFileChanged, setUploadFileChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [dataFormValues, setDataFormValues] = useState({});
  const [activeTabKey, setActivityKey] = useState<any>('1');

  // console.log(dataImgFormValues);

  //提交表单
  const okImageHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      
      console.log("submit fields ", fieldsValue)

      var submitValue = [
        {
          //请求当前一组配置参数，tag=storageImages
          "alias_key": 'storageImages',
          "item_type":'system',
          "dict_item_arr": [
            {
              'alias_key': "images_service",
              'item_value': fieldsValue.images_service,
              'item_type':"select",
            },
            {
              "alias_key": "images_secret_id",
              "item_value": fieldsValue.images_secret_id,
              'item_type':"text",
            },
            {
              "alias_key": "images_secret_key",
              "item_value": fieldsValue.images_secret_key,
              'item_type':"text",
            },
            {
              "alias_key": "images_bucket_name",
              "item_value":fieldsValue.images_bucket_name,
              'item_type':"text",
            },
            {
              "alias_key": "images_bucket_area",
              "item_value": fieldsValue.images_bucket_area,
              'item_type':"text",
            },
            {
              "alias_key": "images_bucket_domain",
              "item_value": fieldsValue.images_bucket_domain,
              'item_type':"url",
            },
            {
              "alias_key": "images_ext",
              "item_value": fieldsValue.images_ext,
              'item_type':"text",
            },
            {
              "alias_key": "images_max_size",
              "item_value": fieldsValue.images_max_size,
              'item_type':"number",
            },
            {
              "alias_key": "images_url_status",
              "item_value": fieldsValue.images_url_status,
              'item_type':"radio",
            },
            {
              "alias_key": "images_url_key",
              "item_value":fieldsValue.images_url_key,
              'item_type':"text",
            },
            {
              "alias_key": "images_url_expire",
              "item_value": fieldsValue.images_url_expire,
              'item_type':"text",
            },
            {
              "alias_key": "images_thumb_avatar",
              "item_value": fieldsValue.images_thumb_avatar,
              'item_type':"text",
            },
            {
              "alias_key": "images_thumb_ratio",
              "item_value":fieldsValue.images_thumb_ratio,
              'item_type':"text",
            },
            {
              "alias_key": "images_thumb_square",
              "item_value": fieldsValue.images_thumb_square,
              'item_type':"text",
            },
            {
              'alias_key': "images_thumb_big",
              'item_value':fieldsValue.images_thumb_big,
              'item_type':"text",
            },
          ]
        }
    ]
    // 如果更新成功之后，重置表单
    updateRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
      console.log('handleSubmit then success is ', JSON.stringify(submitValue))
      if(res.code == 0){
        message.success('保存成功');
        // form.resetFields()
        // setPicture([]);
        // setPictureLogo([]);
      }
    })

    });
  };



  const queryData = (key:any)=>{
    queryRule({item_key: "img_setting"}).then(res=>{
      // setCommon(res.data.common);
      if(res.data.list && res.data.list.length>0){
        setDataFormValues(res.data.list[0]?.item_value_decode);
      }
      // setInitLoading(false);
    });
  }

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      // setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 设置视频图片上传文件值
    const setVideoUploadFile = (fileList:any) => {
      setUploadVideoChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureVideo(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureVideo([])
      }
    }
    // 设置视频图片上传文件值
    const setAudioUploadFile = (fileList:any) => {
      setUploadVideoChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureAudio(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureAudio([])
      }
    }
    // 设置视频图片上传文件值
    const setFileUploadFile = (fileList:any) => {
      setUploadFileChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureFile(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureFile([])
      }
    }

    const parseData = (key:any,options:any) => {
      // console.log(options);
      var name:any = "";
      if(Array.isArray(options) && options.length>0){
        options.map(item=>{
          if(item.alias_key == key){
            name = item?.item_value;
          }
        })
      }
      console.log(name);
      return name
    }

    const parseDataItem = (key:any,options:any) => {
      // console.log(options);
      var obj:any = {};
      if(Array.isArray(options) && options.length>0){
        options.map(item=>{
          if(item.alias_key == key){
            obj = item;
          }
        })
      }
      console.log(obj);
      return obj
    }


  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(parseData('repair_image',imageValues))
  const defaultVideoPicture = DataHelper.buildFileByUrl(parseData('repair_video',imageValues))
  const defaultAudioPicture = DataHelper.buildFileByUrl(parseData('repair_audio',imageValues))
  const defaultFilePicture = DataHelper.buildFileByUrl(parseData('repair_doc',imageValues))

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadVideoButton = DataHelper.showUploadBtn(isUpdate, pictureVideo, defaultVideoPicture, uploadVideoChanged)
  const showUploadAudioButton = DataHelper.showUploadBtn(isUpdate, pictureAudio, defaultAudioPicture, uploadAudioChanged)
  const showUploadFileButton = DataHelper.showUploadBtn(isUpdate, pictureFile, defaultFilePicture, uploadFileChanged)

  // 弹出框
  // @ts-ignore
  return <div>
    <Card title={'存储设置'} className={styles.card} bordered={false}>
        <Row gutter={16}>
          <Col lg={6} md={12} sm={24}>
            <FormItem label={'存储服务商'}>
              {form.getFieldDecorator('images_service', {
                initialValue: parseData('images_service',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Select allowClear={true} placeholder={'存储服务商可在应用商店安装更多选择'} size={'default'} style={{ width: '100%' }}>
              {common.imageOption  && TsxHelper.buildSelectOption(common.imageOption)}
              </Select>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem label={'Secret ID'}>
              {form.getFieldDecorator('images_secret_id', {
                initialValue: parseData('images_secret_id',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
            <FormItem label={'Secret Key'}>
              {form.getFieldDecorator('images_secret_key', {
                initialValue: parseData('images_secret_key',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
            </FormItem>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col lg={6} md={12} sm={24}>
            <FormItem label={
              <span>
                <FormattedMessage id="存储配置名称" />
                {/* <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="如果用户角色有单独设置将以用户角色为准" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em> */}
              </span>
            }>
              {form.getFieldDecorator('images_bucket_name', {
                initialValue: parseData('images_bucket_name',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem label={
              <span>
                <FormattedMessage id="存储配置地域" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="存储配置地域，用不到则留空" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('images_bucket_area', {
                initialValue: parseData('images_bucket_area',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={'用不到则留空'}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
            <FormItem label={
              <span>
                <FormattedMessage id="存储配置域名" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="存储配置域名以 http:// 或 https:// 开头，结尾不带 /" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('images_bucket_domain', {
                initialValue: parseData('images_bucket_domain',dataImgFormValues),
                rules: [{ pattern: /(http|https):\/\/([\w.]+\/?)\S*(?<![/])$/, message: '请输入合法域名 http:// 或 https:// 开头，结尾不带 /'}],
              })(<Input placeholder={'http:// 或 https:// 开头，结尾不带 /'}/>)}
            </FormItem>
          </Col>
        </Row>
    </Card>

    <Card title={'功能配置'} className={styles.card} bordered={false}>
        <Row gutter={16}>
          <Col lg={6} md={12} sm={24}>
            <FormItem label={'支持的扩展名'} extra="">
              {form.getFieldDecorator('images_ext', {
                initialValue: parseData('images_ext',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={'以英文逗号 , 隔开'}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem 
            label={
              <span>
                <FormattedMessage id="支持的最大尺寸" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="如果用户角色有单独设置将以用户角色为准" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('images_max_size', {
                initialValue: parseData('images_max_size',dataImgFormValues),
                rules: [{ pattern: /^[0-9]*$/, message: '输入合理的尺寸大小' }],
              })(<Input style={{width:'100%'}} addonAfter="MB" placeholder={''}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
            
          </Col>
        </Row>
        
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
            <FormItem 
            label={
              <span>
                <FormattedMessage id="防盗链功能" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="如果插件不支持防盗链功能，请勿开启，否则将导致资源无法访问" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('images_url_status', {
                initialValue: parseData('images_url_status',dataImgFormValues) || false,
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>关闭</Radio>
              <Radio value={true}>开启</Radio>
            </Radio.Group>)}
            </FormItem>
            </Col>
            {form.getFieldValue("images_url_status") == true &&<>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <FormItem 
              label={
                <span>
                  <FormattedMessage id="防盗链 Key" />
                  <em className={styles.optional}>
                    <Tooltip title={<FormattedMessage id="用于生成访问 Token" />}>
                      <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                    </Tooltip>
                  </em>
                </span>
              } >
                {form.getFieldDecorator('images_url_key', {
                  initialValue: parseData('images_url_key',dataImgFormValues),
                  // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
                })(<Input placeholder={''}/>)}
              </FormItem>
            </Col>
            <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
              <FormItem 
              label={
                <span>
                  <FormattedMessage id="防盗链签名有效期" />
                  {/* <em className={styles.optional}>
                    <Tooltip title={<FormattedMessage id="用于生成访问 Token" />}>
                      <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                    </Tooltip>
                  </em> */}
                </span>
              }>
                {form.getFieldDecorator('images_url_expire', {
                  initialValue: parseData('images_url_expire',dataImgFormValues),
                  rules: [{ pattern: /^[0-9]*$/, message: '请输入合理得有效期值' }],
                })(<Input addonAfter="分钟" placeholder={''} style={{width:'100%'}}/>)}
              </FormItem>
            </Col>
            </>}
          </Row>
        
        
      </Card>

      <Card title={
        <span>
        <FormattedMessage id="图片处理功能配置" />
        <em className={styles.optional}>
          <Tooltip title={<FormattedMessage id="可以配置样式名或高级参数，实时处理图片，可以压缩、缩放、打水印等各种功能，常见的“间隔标识符”为半角字符 “!”、“-”、“_” 三种。支持高级参数，写法见存储服务商的开发者文档。" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em>
      </span>
      } className={styles.card} bordered={false}>
        <Row gutter={16}>
          <Col lg={6} md={12} sm={24}>
            <FormItem label={'配置图'}>
              {form.getFieldDecorator('images_thumb_config', {
                initialValue: parseData('images_thumb_config',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={''}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem label={'头像图'}>
              {form.getFieldDecorator('images_thumb_avatar', {
                initialValue: parseData('images_thumb_avatar',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={''}/>)}
            </FormItem>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col lg={6} md={12} sm={24}>
            <FormItem label={'等比例缩略图'}>
              {form.getFieldDecorator('images_thumb_ratio', {
                initialValue: parseData('images_thumb_ratio',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={''}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem label={'正方形缩略图'}>
              {form.getFieldDecorator('images_thumb_square', {
                initialValue: parseData('images_thumb_square',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={''}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            <FormItem label={'原图压缩图'}>
              {form.getFieldDecorator('images_thumb_big', {
                initialValue: parseData('images_thumb_big',dataImgFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input placeholder={''}/>)}
            </FormItem>
          </Col>
          <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
            
          </Col>
          <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
            
          </Col>
        </Row>
    </Card>


    <Col span={24}>
      <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
        <Button type="primary" style={{marginLeft:30}} onClick={()=>{okImageHandle()}}>保存</Button>
      </div>
    </Col>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </div>;
};

export default Form.create<DataFormProps>()(DataForm);
